#include "StdAfx.h"
#include "TPGradientCenterPolygon.h"
#include "math.h"
CTPGradientCenterPolygon::CTPGradientCenterPolygon(void)
{
}

CTPGradientCenterPolygon::~CTPGradientCenterPolygon(void)
{
}

BOOL CTPGradientCenterPolygon::FillColor( LPVOID pColorData, BYTE* & pBuffer, int nWidth, int nHeight, eBufferFormat eFormat )
{
	FillInCMethod(pColorData, pBuffer, nWidth, nHeight,eFormat);
	return TRUE;
}

int CTPGradientCenterPolygon::SaveColorToBuffer( LPVOID pColorDef, LPVOID lpBuffer, int nLength )
{
	return 0;
}

int CTPGradientCenterPolygon::LoadColorFromBuffer( LPVOID hColor,LPVOID lpBuffer,int nLength )
{
	return 0;
}

BOOL CTPGradientCenterPolygon::FillInCMethod( LPVOID pColorData, BYTE* & pBuffer, int nWidth, int nHeight, eBufferFormat eFormat )
{
	TPCircleCenterGradientColor* pColorInfo = (TPCircleCenterGradientColor*)pColorData;
	float fRadius = sqrtf(nWidth * nWidth + nHeight * nHeight) / 2;
	float fTheta = asin(nHeight / (2*fRadius));
	TPColorValue* pTable = NULL;
	InitColorTable(fRadius, pTable, pColorInfo->pGradientNode, pColorInfo->nNodeCount, pColorInfo->repeatInfo.dwRepeatCount, pColorInfo->repeatInfo.bRevert);
	
	int fDis = 0;
	BYTE* pCurrent = pBuffer;
	for (int i=0;i<nHeight;i++)
	{
		for (int j=0;j<nWidth;j++)
		{
			if (InHorTraingle(nWidth,nHeight,j-nWidth/2,nHeight/2-i))
			{
				fDis = (int)fabs((float)(nHeight/2 - i)) / sin(fTheta);
			}
			else
			{
				fDis = (int)fabs((float)(j-nWidth/2)) / cos(fTheta);
			}
			pCurrent[0] = TPGetRValue(pTable[fDis]);
			pCurrent[1] = TPGetGValue(pTable[fDis]);
			pCurrent[2] = TPGetBValue(pTable[fDis]);
			pCurrent[3] = TPGetAValue(pTable[fDis]);
			pCurrent+=4;
			
		}
	}
	delete[] pTable;
	return TRUE;
}

BOOL CTPGradientCenterPolygon::InHorTraingle(int nWidth,int nHeight, float nX, float nY )
{
	int fDirection[4][2];
	fDirection[0][0] = -nWidth/2;
	fDirection[0][1] = nHeight/2;

	fDirection[1][0] = nWidth/2;
	fDirection[1][1] = nHeight/2;

	fDirection[2][0] = nWidth/2;
	fDirection[2][1] = -nHeight/2;

	fDirection[3][0] = -nWidth/2;
	fDirection[3][1] = -nHeight/2;

	BOOL bInTran1 = MultiVector(fDirection[0][0],fDirection[0][1],nX,nY) * MultiVector(fDirection[1][0],fDirection[1][1],nX,nY) <=0;
	BOOL bInTran2 = MultiVector(fDirection[2][0],fDirection[2][1],nX,nY) * MultiVector(fDirection[3][0],fDirection[3][1],nX,nY) <=0;

	if (bInTran1 ||  bInTran2)
	{
		return TRUE;
	}
	return FALSE;
}

float	CTPGradientCenterPolygon::MultiVector(float fStart1, float fEnd1,float fStart2, float fEnd2)
{
	return fStart1*fEnd2 - fEnd1*fStart2;
}

